﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cocos2d;
using Meteorite;
using Microsoft.Xna.Framework;
using System.Diagnostics;
using ChaseCameraSample;

using OpenXLive;
using OpenXLive.Forms;
using OpenXLive.Features;
using Microsoft.Xna.Framework.Input;
using CocosDenshion;

namespace Meteorite
{
    public class GameScene : CCScene
    {
        public ControlPad Controler = null;

        CCLabelBMFont Score;
        CCMenuItemImage BtnPause;

        PauseLayer Pauselayer;

        public static int nScore = 0;
        public int nGameOverCountDown = 60;

        float PlayTime;
        public GameScene()
        {
            nScore = 0;
            Pauselayer = null;

            CCSize size = CCDirector.sharedDirector().getWinSize();

            //Title
            Score = CCLabelBMFont.labelWithString("Score", GameConstant.Font_Futura_48);
            addChild(Score);
            Score.position = new CCPoint(0, size.height - 60);
            Score.anchorPoint = new CCPoint(0,0);

            //Menu
            BtnPause = CCMenuItemImage.itemFromNormalImage(GameConstant.Texture_Btn_Pause_N, GameConstant.Texture_Btn_Pause_S, BtnPause, this.menuCallback);
            BtnPause.position = new CCPoint(size.width - 60, size.height - 40);

            CCMenu pMenu = CCMenu.menuWithItems(BtnPause);
            pMenu.position = new CCPoint(0, 0);
            addChild(pMenu);



            Meteorite.ship.Born();
            Vector3 shipPos = Vector3.Zero;
            shipPos.Z = Meteorite.camera.Position.Z - GameConstant.CameraNormalDistance;
            Meteorite.ship.Position = shipPos;
            Meteorite.camera.StopShake();

            Controler = new ControlPad();
            Controler.position = new CCPoint(Controler.contentSize.width / 2, Controler.contentSize.height / 2);

            addChild(Controler);


            schedule(Tick,0.03f);

            UserData.Instance().AddValue(GameConstant.UserData_TotalGamesPlayed, 1);
        }
        public override void onEnter()
        {
            base.onEnter();

            if (0 == UserData.Instance().GetValue(GameConstant.UserData_Sound))
            {
                SimpleAudioEngine.sharedEngine().playBackgroundMusic(CCFileUtils.fullPathFromRelativePath(GameConstant.Sound_Game_Bkg), true);
            }
        }

        public void Tick(float dt)
        {
            if( !Meteorite.ship.Valid )
            {
                if(nGameOverCountDown<=0)
                {
                    UserData.Instance().AddValue(GameConstant.UserData_TotalPlayTime, (int)PlayTime);
                    UserData.Instance().SetValue(GameConstant.UserData_LastPlayTime, (int)PlayTime);
                    UserData.Instance().SetValue(GameConstant.UserData_LastScore, nScore);
                    if (nScore > UserData.Instance().GetValue(GameConstant.UserData_HighScore))
                    {
                        UserData.Instance().SetValue(GameConstant.UserData_HighScore, nScore);
                    }
                    UserData.Instance().Save();
                    Leaderboard lb = new Leaderboard(Meteorite.livemanager.CurrentSession, GameConstant.XLiveLeaderBoardKey);
                    lb.SubmitScore(nScore);
                    CCScene pScene = new GameOverScene(nScore);
                    CCDirector.sharedDirector().replaceScene(pScene);
                    
                }
                else
                {
                    nGameOverCountDown--;
                }
                return;
            }
            PlayTime += dt;
            if (Meteorite.Pause)
            {
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {//this doesn't work,why?
                    Meteorite.Pause = false;
                    if( null!=Pauselayer )
                    {
                        removeChild(Pauselayer,true);
                        Pauselayer = null;
                    }
                    
                }
                else
                {
                    return;
                }
            }
            //score
            
            Score.setString("Score" + nScore.ToString());
            
            Controler.Loop();

            //control the ship
            /*
            CCPoint percent = Controler.GetOffsetPercent();
            Vector3 Force = Vector3.Zero;
            Force.X = percent.x * GameConstant.ThrustForce;
            Force.Y = percent.y * GameConstant.ThrustForce;
            
            Meteorite.ship.Force = Force;
            */
            
            //Meteorite.ship.Update(gameTime);

            //Debug.WriteLine("1----{0}", Meteorite.ship.Force);
            //Process camera
            ChaseCamera camera = Meteorite.camera;
            if (!camera.IsShaking())
            {
                float Distance = camera.Position.Z - Meteorite.ship.Position.Z;
                float ShapeRange = 0.0f;
                if (Distance > GameConstant.CameraShakeDistance)
                {
                    ShapeRange = Math.Abs(Distance / GameConstant.CameraShakeDistance);
                    camera.Shake(10, 1, ShapeRange);
                }
                else
                {
                    //ShapeRange = GameConstant.CameraMaxShakeRange;
                    //camera.Shake(10, 3, ShapeRange);
                }
            }

            Meteorite.camera.ChasePosition = Meteorite.ship.Position;
            Meteorite.camera.ChaseDirection = Vector3.Forward;
            Meteorite.camera.Up = Vector3.Up;

            foreach (Object o in Meteorite.stoneManager.GetEntityList())
            {
                if (Meteorite.ship.Valid && o.Valid)
                {
                    if (Meteorite.ship.CheckCollision(o))
                    {
                        o.CollideWithShip(Meteorite.ship);
                    }
                }
            }

            //OpenXlive achievement
            if (50 == nScore)
            {
                Achievement item = new Achievement(Meteorite.livemanager.CurrentSession, GameConstant.XLiveAchievement_1);
                item.AwardCompleted += new AsyncEventHandler(item_AwardCompleted);
                item.Award();
            }
            if (100 == nScore)
            {
                Achievement item = new Achievement(Meteorite.livemanager.CurrentSession, GameConstant.XLiveAchievement_2);
                item.AwardCompleted += new AsyncEventHandler(item_AwardCompleted);
                item.Award();
            }

            if (0 == nScore % 50 )
            {
                Leaderboard lb = new Leaderboard(Meteorite.livemanager.CurrentSession, GameConstant.XLiveLeaderBoardKey);
                lb.SubmitScore(nScore);
            }
        }
        public void Pause()
        {
            if (!Meteorite.Pause)
            {
                Pauselayer = new PauseLayer();
                addChild(Pauselayer);
                Meteorite.Pause = true;
            }
        }
        public void Resume()
        {
            if (null!=Pauselayer)
            {
                removeChild(Pauselayer,true);
            }
            Meteorite.Pause = false;
        }
        public void menuCallback(CCObject pSender)
        {
            if (pSender == BtnPause)
            {
                Pause();
            }
            if (0 == UserData.Instance().GetValue(GameConstant.UserData_Sound))
            {
                SimpleAudioEngine.sharedEngine().playEffect(CCFileUtils.fullPathFromRelativePath(GameConstant.Sound_Btn));
            }
        }

        void item_AwardCompleted(object sender, AsyncEventArgs e)
        {
            if (e.Result.ReturnValue)
            {
                // Success
                Achievement item = sender as Achievement;
                if (Meteorite.NewsBoard != null)
                {
                    Meteorite.NewsBoard.AddNews(new RollingNews(item.Name, item.Description,item.Image));
                }
            }
            else
            {
                Debug.WriteLine(e.Result.ErrorMessage);
            }
        }
    }
}
